package cn.bistu.cs.haroldweather;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;

import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.TouchDelegate;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.litepal.LitePal;


import java.io.IOException;
import java.util.List;

import cn.bistu.cs.haroldweather.db.Focuses;
import cn.bistu.cs.haroldweather.db.WeatherInfo;
import cn.bistu.cs.haroldweather.gson.Weather;
import cn.bistu.cs.haroldweather.util.HttpUtil;
import cn.bistu.cs.haroldweather.util.Utility;
import cn.bistu.cs.haroldweather.viewpager.Fragment1;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private EditText adcode;
    private Button button_search;
    private Button nav_button;
    private TextView title_province;
    private TextView degree_text;
    private TextView humidity_text;
    private TextView weather_info_text;
    private TextView winddirection;
    private TextView city;
    private TextView updateTime;
    public DrawerLayout drawerLayout;
    public SwipeRefreshLayout swipeRefreshLayout;
    private String address;
    public Button floatingActionButton;
    public Weather weather;
    private Button focuslist;
    public int flag=0;
    private WeatherInfo weatherInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_weather);
        LitePal.initialize(this);
        adcode = findViewById(R.id.adcode);
        button_search = findViewById(R.id.button_search);
        title_province = findViewById(R.id.title_province);
        degree_text = findViewById(R.id.degree_text);
        humidity_text = findViewById(R.id.humidity_text);
        weather_info_text = findViewById(R.id.weather_info_text);
        winddirection = findViewById(R.id.winddirection);
        city = findViewById(R.id.city);
        updateTime = findViewById(R.id.updateTime);
        nav_button = findViewById(R.id.nav_button);
        drawerLayout = findViewById(R.id.drawer);
        floatingActionButton = findViewById(R.id.floatButton);
        swipeRefreshLayout = findViewById(R.id.swipe_refresh);
        focuslist = findViewById(R.id.focuslist);
        focuslist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                drawerLayout.openDrawer(GravityCompat.END);
            }
        });
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (flag){
                    case 0:
                        if(checkFocues()&&weatherInfo!=null){
                            floatingActionButton.setText("取消关注");
                            floatingActionButton.setActivated(false);
                            flag=1;
                            Focuses focuses = new Focuses(weatherInfo.province,weatherInfo.city,weatherInfo.distraction,weatherInfo.adcode);
                            focuses.save();
                            Toast.makeText(MainActivity.this,"收藏成功,点击右侧关注列表并点击刷新即可查看",Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(MainActivity.this,"该地区已经被关注！或者 您还未选择地区！",Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 1:
                        Toast.makeText(MainActivity.this,"取消收藏成功",Toast.LENGTH_SHORT).show();
                        floatingActionButton.setText("点击关注");
                        LitePal.deleteAll(Focuses.class,"adcode=?",adcode.getText().toString());
                        floatingActionButton.setActivated(true);
                        flag=0;
                        break;
                }
            }
        });

        button_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                address = adcode.getText().toString();
                getWeather(address,0);

            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                address = adcode.getText().toString();
                getWeather(address,1);
            }
        });
        nav_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
    }
    /*
    检查该地区是否被关注
     */
    public boolean checkFocues(){
        swipeRefreshLayout.setRefreshing(false);
        if(weatherInfo!=null){
            String adcode = weatherInfo.adcode;
            Log.e("focuese值",""+LitePal.where("adcode=?",adcode).find(Focuses.class).size());
            if(LitePal.where("adcode=?",adcode).find(Focuses.class).size()>0){
                floatingActionButton.setText("已关注");
                floatingActionButton.setActivated(false);
                flag=1;
                return false;
            }else{
                floatingActionButton.setText("点击关注");
                flag=0;
            }
        }
        return true;

    }
    /*
    获取天气
     */
    public void getWeather(final String address, int tag){
        if(tag==0){
            List<WeatherInfo>  lives = LitePal.where("adcode=?",address).find(WeatherInfo.class);
            //如果数据库里有这个地方的天气数据，则直接显示
            if(!lives.isEmpty()){
                weatherInfo = lives.get(lives.size()-1);
                showInfo(weatherInfo);
                Log.e("Litepal",lives.get(lives.size()-1).toString());
                swipeRefreshLayout.setRefreshing(false);
                return;
            }
        }
        if(address!=null&&!address.equals("")){
            String dataurl = "http://guolin.tech/api/weather?cityid=" + address + "&key=bc0418b57b2d4918819d3974ac1285d9";
            Log.e("url",dataurl);
            HttpUtil.sendOkHttpRequest(dataurl, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    swipeRefreshLayout.setRefreshing(false);
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String responseContent = response.body().string();
//                        int index = responseContent.indexOf("[");
//                        Log.e("index",index+"");
                    Log.e("responseContent",responseContent);
                    if(responseContent==null||responseContent.equals("")){
                        Toast.makeText(MainActivity.this,"输入的adcode有误！",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //Log.e("print",Character.toString(responseContent.charAt(index+1)));
                    if(responseContent.equals("Request weather info with error: undefined method `city_id' for nil:NilClass")){
                        Looper.prepare();
                        Toast.makeText(MainActivity.this, "输入城市adcode有误！", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                        return;
                    }
                    weather = Utility.handleWeatherResponse(responseContent);
                    weatherInfo = new WeatherInfo(weather);
                    weatherInfo.save();//保存到数据库
                    Log.e("weather",weather.toString());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(weatherInfo!=null&&weatherInfo.status.equals("ok")){
                                //sharedpreferences
                                showInfo(weatherInfo);
                            }else{
                                Toast.makeText(MainActivity.this,"没有获取天气！",Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    swipeRefreshLayout.setRefreshing(false);
                }
            });
        }else{
            swipeRefreshLayout.setRefreshing(false);
            Toast.makeText(MainActivity.this,"请先输入城市编号！",Toast.LENGTH_SHORT).show();
        }

    }

    /*
    展示天气
     */
    public void showInfo(WeatherInfo weather){
        title_province.setText(weather.city);
        city.setText(weather.distraction);
        degree_text.setText(weather.temperature+"℃");
        humidity_text.setText("湿度："+weather.humidity);
        winddirection.setText("风向："+weather.winddirection);
        weather_info_text.setText("天气状况："+weather.info);
        adcode.setText(weather.adcode);
        updateTime.setText("更新日期："+weather.updateTime);
    }
}